package controllers;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.GregorianCalendar;

import play.Logger;

public abstract class Utile {

	public static Date stringToDate(final String d) throws ParseException {
		final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
		final Date date = sdf.parse(d);
		return date;
	}

	public static String dateToString(final GregorianCalendar gc)
			throws ParseException {
		final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
		final Date date = gc.getTime();
		final String retourn = sdf.format(date);
		return retourn;
	}

	public static String generateCle() {
		final String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		// String nums = "1234567890";
		final int charLength = chars.length();// +nums.length();
		final StringBuilder pass = new StringBuilder(charLength);
		for (int x = 0; x < 5; x++) {
			final int i = (int) (Math.random() * charLength);

			pass.append(chars.charAt(i));
		}
		return pass.toString();
	}

	public static String generateMD5(final String password) {
		String res = "";
		try {
			MessageDigest md;

			md = MessageDigest.getInstance("MD5");

			md.update(password.getBytes());

			final byte byteData[] = md.digest();

			// convert the byte to hex format method 1
			final StringBuffer sb = new StringBuffer();
			for (int i = 0; i < byteData.length; i++) {
				sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16)
						.substring(1));
			}
			res = sb.toString();
		} catch (NoSuchAlgorithmException e) {
			Logger.debug(e.getMessage());
		}
		return res;
	}

}
